package util;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Base64;

/**
 * @description ASE加密工具包
 * @author lincat
 * @finish-time 2022-3-10
 */
public class AESUtil {

    private final String ALGORITHM = "AES";

    private SecretKey secretKey;

    /**
     * @description 工具包的构造函数：根据加密种子生成一个密钥实例
     * @param bt
     * @throws NoSuchAlgorithmException
     */
    public AESUtil(String bt) throws NoSuchAlgorithmException {
        //获取一个密钥生成器实例
        KeyGenerator keyGenerator = KeyGenerator.getInstance(ALGORITHM);
        SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
        //设置加密用的种子，密钥
        random.setSeed(bt.getBytes());
        keyGenerator.init(random);
        this.secretKey = keyGenerator.generateKey();
    }

    /**
     * @description 加密
     * @param content
     * @return
     * @throws Exception
     */
    public String encode(String content) throws Exception {
        //指定算法、获取Cipher对象
        Cipher cipher = Cipher.getInstance(ALGORITHM);
        //用指定的密钥初始化Cipher对象，指定是加密模式，还是解密模式
        cipher.init(Cipher.ENCRYPT_MODE, this.secretKey);
        //更新需要加密的内容
        cipher.update(content.getBytes());
        //进行最终的加解密操作,加密后的字节数组
        byte[] bytesResult = cipher.doFinal();
        //对加密后的字节数组进行Base64编码
        String base64Result = Base64.getEncoder().encodeToString(bytesResult);
        return  base64Result;
    }

    /**
     * @description 解密
     * @param content
     * @return
     * @throws Exception
     */
    public String decode(String content) throws Exception{
        Cipher cipher = Cipher.getInstance(ALGORITHM);
        cipher.init(Cipher.DECRYPT_MODE, this.secretKey);
        byte[] encodedBytes = Base64.getDecoder().decode(content.getBytes());
        //对加密后的字节数组进行解密
        byte[] bytesResult = cipher.doFinal(encodedBytes);
        String result = new String(bytesResult);
        return result;
    }
}
